﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using com.iss.inventory.Entity;
using System.Text;
using System.Data;
using System.IO;
using System.Net.Mail;
using com.iss.inventory.CustomModels;
using com.iss.inventory;


namespace StationeryInv
{
    public partial class PurchaseOrders : System.Web.UI.Page
    {
        MainController mc;
       // List<StationeryItem> itemList = new List<StationeryItem>();

        //Populates form with UserName
        protected void Page_Load(object sender, EventArgs e) 
        {
            if (Session["empID"] == null)
            {
                Response.Redirect("~/Presentation/login.aspx");
            }
            Label lbl = this.Master.FindControl("lblLogInName") as Label;
            if (lbl != null)
            {
                lbl.Text = Session["UserName"].ToString();
            }

          
            //Create lists of Show Purchase Orders models for populating gridview
            List<ShowPo> lisshow = new List<ShowPo>();
            List<ShowPo> lisshow1 = new List<ShowPo>();
            List<ShowPo> currentitems = new List<ShowPo>();
            List<ShowPo> currentitems1 = new List<ShowPo>();
          

            //locks state of dropdownlist, if user selects a specific supplier 
            if (Request.UrlReferrer != null)
            {
                string prevurl1 = Request.UrlReferrer.ToString();
                if (prevurl1.Contains("SupplierItemsforDO.aspx"))
                {
                    ddlSupplier.SelectedValue = (String)Session["SupplierName"];
                    ddlSupplier.Enabled = false;
                }

            }

           
            if (!IsPostBack)
            {
              

                InvManagementEntities invent1 = new InvManagementEntities();
                
                //Populate Purchase Order Number, DateTime, Attention to Label, automatically
                int value = int.Parse(invent1.PurchaseOrders
                            .OrderByDescending(p => p.PurchaseID)
                            .Select(r => r.PurchaseID)
                            .First().ToString());
                int a = value + 1;

                tbPONumber.Text = Convert.ToString(a);
                Session["tbPONumber"] = tbPONumber.Text;


                DateTime dateonly = DateTime.Now.Date;
                tbOrderedDate.Text = dateonly.ToString("dd-MM-yyyy");
                tbApprovedDate.Text = dateonly.ToString("dd-MM-yyyy");

                DateTime requireddate = DateTime.Today.AddDays(7);
                tbReqDate.Text = requireddate.ToString("dd-MM-yyyy");


                lblAttnTo.Text = ddlOrderedBy.SelectedValue;
                
                
                    {
                        InvManagementEntities invent = new InvManagementEntities();




                        //locks state of dropdownlist, if user selects a specific supplier 
                        if (Request.UrlReferrer != null && Session["Search_allselecteddata"]!=null)
                        {
                            ddlSupplier.SelectedValue = (String)Session["SupplierName"];
                            ddlSupplier.Enabled = false;
                            string prevurl = Request.UrlReferrer.ToString();

                            //Gets list of items from Search Page(Only for specific supplier from dropdownlist)
                            if (prevurl.Contains("SearchItemsPage.aspx"))
                            {
                                List<StationeryItem> lisshow1_temp = new List<StationeryItem>();
                           

                                lisshow1_temp = Session["Search_allselecteddata"] as List<StationeryItem>;

                                foreach (StationeryItem si in lisshow1_temp)
                                {
                                    ShowPo sh = new ShowPo();
                                    sh.ItemID = si.ItemID;
                                    sh.Description = si.Description;
                                    sh.Qty = (int)si.QtyLeft;

                                    int itemID = si.ItemID;
                                    int reorderqty = (int)(from si1 in invent.StationeryItems
                                                           where si1.ItemID == itemID
                                                           select si1.ReorderQty).First();
                                    sh.Qty = reorderqty;

                                    double unitprice = double.Parse((from spl in invent.SupplierPriceLists
                                                                     where spl.ItemID == itemID && spl.SupplierCategory == 1
                                                                     select spl.SupplierPrice).First().ToString());
                                    sh.Price = unitprice;
                                    sh.Amount = reorderqty * unitprice;

                                    lisshow1.Add(sh);

                                   
                                }
                            }
                        }
                        
                        
                        
                        //Save gridview items and state into sessions
                        lisshow = Session["SupplierItemsDO"] as List<ShowPo> ;
                
                        currentitems = Session["CurrentItems"] as List<ShowPo>;

                      

                       
                        
                        //combining data from previous pages into 1 list and populating gridview
                        if(Session["CurrentItems"]!=null)
                        {
                            if (Session["SupplierItemsDO"] != null)
                            {
                                currentitems.AddRange(lisshow);
                                Session["SupplierItemsDO"] = null;

                            }

                           
                            else if (Session["Search_allselecteddata"] != null)
                            {
                                currentitems.AddRange(lisshow1);
                                
                                Session["Search_allselecteddata"] = null;
                            }

                            Session["CurrentItems"]=null;
                        }
                                             
                        GviewPO.DataSource = currentitems;
                        GviewPO.DataBind();

                    }
                
               
                //Calculating GrandTotal Textbox
                    Double grandtotal = 0;
                    foreach (GridViewRow gvrow in GviewPO.Rows)
                    {
                        TextBox txt3 = gvrow.FindControl("SubtotalAmount") as TextBox;
                        Double subtotal = Convert.ToDouble(txt3.Text);
                        grandtotal += subtotal;

                    }

                    tbGrandTotal.Text = Convert.ToString(grandtotal);

                }
           

        }



        //Render Gridview to Html to be sent in mail
        public string GridViewtoHtml(GridView GviewPO)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GviewPO.RenderControl(hw);
            return sb.ToString();
        } 

        
       // Confirms that the HtmlForm control is rendered for the Gridview
        public override void VerifyRenderingInServerForm(Control control)
        {
            
        }

        //submit to supplier and populate database with records
        protected void btnSubmitToSupplier_Click(object sender, EventArgs e)
        {
            //Populate the Attention To Label with the clerk who ordered
            lblAttnTo.Text = ddlOrderedBy.SelectedValue;

            //check submitted date no earlier than today
            if (Convert.ToDateTime(tbReqDate.Text) <= DateTime.Now.Date)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Please enter a date later than today')", true);

            }


            //select supplier email
            InvManagementEntities invent = new InvManagementEntities();
            string email2 = (from sl in invent.Suppliers
                        where sl.Name == ddlSupplier.SelectedValue
                        select sl.Email).First();
            


            //send email
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("sa37inv@gmail.com");
            mail.To.Add(new MailAddress(email2));
            mail.Subject = "Purchase Order from Logic University; Purchase Order:" + tbPONumber.Text.ToString();
            mail.Body = "Please supply the following items by:" + tbReqDate.Text.ToString() +"<br />";
            mail.Body += GridViewtoHtml(this.GviewPO) + "<br />";
            mail.Body += "Ordered by:" + ddlOrderedBy.SelectedValue + "\t" + "\t"+ "Date Ordered:" + tbOrderedDate.Text.ToString() + "<br />";
            mail.Body += "Authorised by:" + ddlApprovedBy.SelectedValue + "\t" + "\t" + "Date Ordered:" + tbApprovedDate.Text.ToString() + "<br />";
            mail.IsBodyHtml = true;

            SmtpClient sc = new SmtpClient();
            sc.Host = "smtp.gmail.com";
            sc.Port = 25;
            sc.Credentials = new System.Net.NetworkCredential("sa37inv@gmail.com", "sa37inv1");
            sc.EnableSsl = true;
            sc.Send(mail);




            //Save values to database
         
            var addtoPO = new com.iss.inventory.Entity.PurchaseOrder();

            var addtoDO = new com.iss.inventory.Entity.DeliveryOrder();

            ////add to Delivery Order Table
            addtoDO.PurchaseID = Convert.ToInt32(tbPONumber.Text);
            invent.AddToDeliveryOrders(addtoDO);
            invent.SaveChanges();

            // add to Purchase Order Table
             int supplierid = (from sl in invent.Suppliers
                        where sl.Name == ddlSupplier.SelectedValue
                        select sl.SupplierID).First();
             addtoPO.SupplierID = supplierid;

             int deliveryorderid = int.Parse(invent.DeliveryOrders
                                    .OrderByDescending(p => p.DeliveryID)
                                    .Select(r => r.DeliveryID)
                                    .First().ToString());
             addtoPO.DeliveryOrderID = deliveryorderid;

             int orderedbyid = (from emp in invent.Employees
                                where emp.Name == ddlOrderedBy.SelectedValue
                                select emp.EmployeeID).First();
             addtoPO.OrderedbyID = orderedbyid;

             addtoPO.DateOrdered = Convert.ToDateTime(DateTime.Now.Date) ;
             addtoPO.DateRequired = Convert.ToDateTime(tbReqDate.Text);

             invent.AddToPurchaseOrders(addtoPO);
             invent.SaveChanges();

            //add to Purchase Order Details Table
             foreach (GridViewRow gvrow in GviewPO.Rows)
             {
                 var addtoPODetails = new PurchaseOrderDetail();
                 addtoPODetails.PurchaseID = Convert.ToInt32(tbPONumber.Text);
                 addtoPODetails.ItemID = Convert.ToInt32(gvrow.Cells[0].Text);
                 addtoPODetails.Description = Convert.ToString(gvrow.Cells[1].Text);


                 int reorderqty1 = Convert.ToInt32(gvrow.Cells[0].Text);
                 int reorderqty = (int) (from si in invent.StationeryItems
                                    where si.ItemID == reorderqty1
                                    select si.ReorderQty).First();
                 
                 TextBox txt = gvrow.FindControl("QtyPO") as TextBox;
                 int QtyPO = Convert.ToInt32(txt.Text);

                 if (txt.Text !=null)
                 {
                     addtoPODetails.Qty = QtyPO;
                 }

                 double unitprice1 = Convert.ToInt32(gvrow.Cells[0].Text);

                 double unitprice = double.Parse((from spl in invent.SupplierPriceLists
                                  where spl.ItemID == unitprice1 && spl.SupplierCategory == 1
                                  select spl.SupplierPrice).First().ToString());
                 addtoPODetails.UnitPrice = unitprice;

                 TextBox txt1 = gvrow.FindControl("UnitPrice") as TextBox;
                 txt1.Text = Convert.ToString(unitprice);

                 TextBox txt2 = gvrow.FindControl("SubtotalAmount") as TextBox;

                 double qtypo = Convert.ToDouble( txt.Text);
                double subtotalamt = Convert.ToDouble( unitprice * qtypo);
                txt2.Text = Convert.ToString(subtotalamt);


                invent.AddToPurchaseOrderDetails(addtoPODetails);

                invent.SaveChanges();
             
                 }

         ScriptManager.RegisterStartupScript(this, this.GetType(), "redirect",
        "alert('Purchase Order Emailed and Saved Successfully.'); window.location='" +
        Request.ApplicationPath + "Presentation/DeliveryOrder/DeliveryOrder.aspx';", true);    
        }
    
        
        //Redirects to a page, to show inventory items below their re-order levels
        protected void btnShowSuggestions_Click(object sender, EventArgs e)
        {
            Session["SupplierName"] = ddlSupplier.SelectedValue; 

            List<ShowPo> lisshow3 = new List<ShowPo>();
            if (GviewPO.Rows.Count != 0)
            {
                InvManagementEntities invent = new InvManagementEntities();
                
                foreach (GridViewRow gvrow in GviewPO.Rows)
                {
                    ShowPo sh = new ShowPo();
                    
                    {

                        sh.ItemID = int.Parse(gvrow.Cells[0].Text);
                        sh.Description = gvrow.Cells[1].Text;

                        int reorderqty1 = Convert.ToInt32(gvrow.Cells[0].Text);
                        int reorderqty = (int)(from si in invent.StationeryItems
                                               where si.ItemID == reorderqty1
                                               select si.ReorderQty).First();
                        sh.Qty = reorderqty;

                        double unitprice1 = Convert.ToInt32(gvrow.Cells[0].Text);

                        double unitprice = double.Parse((from spl in invent.SupplierPriceLists
                                                         where spl.ItemID == unitprice1 && spl.SupplierCategory == 1
                                                         select spl.SupplierPrice).First().ToString());

                        sh.Price = unitprice;
                        sh.Amount = reorderqty * unitprice;
                        lisshow3.Add(sh);

                    }


                }
            }
            Session["CurrentItems"] = lisshow3;

            Session["b"] = ddlSupplier.SelectedValue;
            Response.Redirect("SupplierItemsforDO.aspx");
        }


        //Redirects to search page, to add any inventory item to purchase
        protected void btnAddItem_Click(object sender, EventArgs e)
        {
            //Save suppliername from dropdownlist into session to lock dropdownlist, when user comes back later
            Session["SupplierName"] = ddlSupplier.SelectedValue; 

            //Passes the values of supplierid to the 'SearchItemsPage' to only filter goods from that specific supplier
            InvManagementEntities invent = new InvManagementEntities();

            int supplierid = (from sl in invent.Suppliers
                              where sl.Name == ddlSupplier.SelectedValue
                              select sl.SupplierID).First();
            Session["Supplierid"] = supplierid;


            String supplieridstring = supplierid.ToString();

            List<SearchItemsModel> criterialist = new List<SearchItemsModel>();
            SearchItemsModel model = new SearchItemsModel();
            model.CriteriaList.Add(supplieridstring);
            Session["searchitemsmodel"] = model;     


            //CHecks current gridview items, and saves it into a session. For populating grid later when user returns
            List<ShowPo> lisshow4 = new List<ShowPo>();
            if (GviewPO.Rows.Count != 0)
            {
                

                foreach (GridViewRow gvrow in GviewPO.Rows)
                {
                    ShowPo sh = new ShowPo();
                   // CheckBox chk = gvrow.FindControl("cbSelectItem") as CheckBox;
                    // if (chk.Checked == true)
                    {

                        sh.ItemID = int.Parse(gvrow.Cells[0].Text);
                        sh.Description = gvrow.Cells[1].Text;

                        int reorderqty1 = Convert.ToInt32(gvrow.Cells[0].Text);
                        int reorderqty = (int)(from si in invent.StationeryItems
                                               where si.ItemID == reorderqty1
                                               select si.ReorderQty).First();
                        sh.Qty = reorderqty;

                        double unitprice1 = Convert.ToInt32(gvrow.Cells[0].Text);

                        double unitprice = double.Parse((from spl in invent.SupplierPriceLists
                                                         where spl.ItemID == unitprice1 && spl.SupplierCategory == 1
                                                         select spl.SupplierPrice).First().ToString());

                        sh.Price = unitprice;
                        sh.Amount = reorderqty * unitprice;
                        lisshow4.Add(sh);

                    }


                }
            }

            
            Session["CurrentItems"] = lisshow4;

            ViewState["PreviousPage"] = "PurchaseOrders.aspx";
            Response.Redirect("~/Presentation/Search/SearchItemsPage.aspx");
        }

        
        //Clears the page of all items
        protected void btnClearFields_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }

        
        //Calculates the Subtotals and GrandTotals on page automatically
        protected void QtyPO_TextChanged(object sender, EventArgs e)
        {
            List <ShowPo> statitem = new List <ShowPo>() ;
            InvManagementEntities invent = new InvManagementEntities();

            foreach (GridViewRow gvrow in GviewPO.Rows)
           
            {
                 ShowPo sp = new ShowPo();
                 sp.ItemID = int.Parse(gvrow.Cells[0].Text);
                 sp.Description = gvrow.Cells[1].Text;

                TextBox txt = gvrow.FindControl("QtyPO") as TextBox;
                int qtypo = Convert.ToInt32(txt.Text);
                 sp.Qty = qtypo;

                 TextBox txt1 = gvrow.FindControl("UnitPrice") as TextBox;
               Double unitprice1 = Convert.ToDouble(txt1.Text);
               sp.Price = unitprice1;

             
                 sp.Amount = qtypo * unitprice1;
                 statitem.Add(sp);



                GviewPO.DataSource = statitem;
                GviewPO.DataBind();
            }

            
            Double grandtotal = 0;
            foreach (GridViewRow gvrow in GviewPO.Rows)
            {
                TextBox txt3 = gvrow.FindControl("SubtotalAmount") as TextBox;
                Double subtotal = Convert.ToDouble(txt3.Text);
                grandtotal += subtotal;

            }

            
            tbGrandTotal.Text = Convert.ToString(grandtotal);

        }

        //Populates 'Attention To' label automatically from dropdownlist of who ordered it
        protected void ddlOrderedBy_Load(object sender, EventArgs e)
        {
            lblAttnTo.Text = ddlOrderedBy.SelectedValue;
        }


        //to lock the supplier name once user selects one name.
        protected void ddlSupplier_SelectedIndexChanged1(object sender, EventArgs e)
        {
            ddlSupplier.Enabled = false;
        }
       
    }
}
